#include "stdafx.h"
#include "Player.h"

#include "AfterBurnerClone.h"

namespace MyGame {

Player::Player(Game* game) : Jet(game) {
    this->SetMaxAcceleration(3);
    this->SetMinAccelration(3);
    this->SetAcceleration(3);
    this->SetDirection(D3DXVECTOR3(0, 0, 1));
    this->SetMaxSpeed(15);
    this->SetMinSpeed(5);
    this->SetSpeed(8);
    this->SetHealth(10);
    this->missiles = 20;
    this->missileSpeed = 20;
    this->missileTurnSpeed = 3.0f;
    this->score = 0;
}

Player::~Player(void) {
}

int Player::GetMissiles() const {
    return this->missiles;
}

void Player::SetMissiles(int val) {
    this->missiles = val < 0 ? 0 : val;
}

int Player::GetScore() const {
    return this->score;
}

void Player::SetScore(int val) {
    this->score = val;
}

void Player::ShootMissile() {
    if (this->missiles == 0) {
        return;
    }

    EnemyController* enemyController = ((AfterBurnerClone*)this->GetGame())->GetEnemyController();
    list<Enemy*>* enemies = enemyController->GetEnemies();
    if (enemies->size() == 0) {
        return;
    }

    for (list<Enemy*>::const_iterator it = enemies->begin(); it != enemies->end(); ++it) {
        Enemy* enemy = *it;
        if (!enemy->GetTargeted() || enemy->GetIncomigMissile() != NULL || enemy->GetState() != FLYINGSTATE_ALIVE) {
            continue;
        }

        Missile* missile = new Missile(this->GetGame());
        missile->SetDirection(this->GetDirection());
        missile->SetPosition(this->GetPosition());
        missile->SetSpeed(this->missileSpeed);
        missile->SetTurnSpeed(this->missileTurnSpeed);
        missile->SetTarget(enemy);
        missile->Initialize();
        missile->LoadContent();
        ((AfterBurnerClone*)this->GetGame())->GetEnemyController()->GetMissiles()->push_back(missile);
        enemy->SetIncomingMissile(missile);
        this->missiles--;

        if (this->missiles == 0) {
            return;
        }
    }
}

void Player::Update(FLOAT timeDelta) {
    EnemyController* enemyController = ((AfterBurnerClone*)this->GetGame())->GetEnemyController();
    list<Enemy*>* enemies = enemyController->GetEnemies();
    for (list<Enemy*>::const_iterator it = enemies->begin(); it != enemies->end(); ++it) {
        Enemy* enemy = *it;
        if (enemy->GetTargeted() || enemy->GetIncomigMissile() != NULL || enemy->GetState() != FLYINGSTATE_ALIVE) {
            continue;
        }

        d3d::BoundingSphere* bs = enemy->GetBoundingSphere();
        D3DXVECTOR3 target = this->GetPosition();
        target.z = bs->_center.z;
        FLOAT dist = D3DXVec3Length(&(target - bs->_center));
        if (dist < bs->_radius) {
            enemy->SetTargeted(true);
        }
    }

    __super::Update(timeDelta);
}

}
